<?php

namespace App\GraphQL\Mutations\User;

use GraphQL\Type\Definition\ResolveInfo;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use App\Models\User;
use App\Models\AdminWallet;
class Create
{
    /**
     * Return a value for the field.
     *
     * @param  null  $rootValue Usually contains the result returned from the parent field. In this case, it is always `null`.
     * @param  mixed[]  $args The arguments that were passed into the field.
     * @param  \Nuwave\Lighthouse\Support\Contracts\GraphQLContext  $context Arbitrary data that is shared between all fields of a single query.
     * @param  \GraphQL\Type\Definition\ResolveInfo  $resolveInfo Information about the query itself, such as the execution state, the field name, path to the field from the root, and more.
     * @return mixed
     */
    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
    {
        
        $data = $args['input'];
        $this->validate($data);
        $data['password'] = bcrypt($data['password']);
        if($data['address']){
            $tmp = explode(',', $data['address']);
            $data['province'] = $tmp[0];
            $data['city'] = $tmp[1];
            $data['area'] = $tmp[2];
        }
        $user = User::create($data);
        AdminWallet::create(['user_id'=>$user->id]);
        return [
            'status'=> '200',
            'message'=>'创建成功'
        ];
    }
    public function validate($data){
        $authUser = auth()->user();
        $roles = [];
        if ($authUser->role_code == 'ADMIN') {
            $roles = ['ADMIN','AGENT','DISTRIBUTOR','MERCHANT','STAFF','REPAIRER','FACTORY'];
        } else if($authUser->role_code == 'AGENT'){
            $roles = ['DISTRIBUTOR','MERCHANT'];
        } else if($authUser->role_code == 'MERCHANT'){
            $roles = ['STAFF'];
        }
        $rules = [
            'name'=>['required','max:18'],
            'phone'=>['required','min:11','max:11'],
            'id_card'=>['required'],
            'password'=>['required'],
            'role_code'=>['required',Rule::in($roles)]
        ];
        $messages = [
            'name.required'=>'姓名不能为空',
            'name.max'=>'姓名不能超过18个字',
            'phone.required'=>'手机号不能为空',
            'phone.min'=>'手机号为11位',
            'phone.max'=>'手机号为11位',
            'id_card.required'=>'身份证不能为空',
            'password.required'=>'密码不能为空',
            'role_code.required'=>'角色不能为空',
            'role_code.in'=>'角色不能超出限制'
        ];
        $validate = Validator::make($data,$rules,$messages);
        if ($validate->fails()) {
            throw new \InvalidArgumentException($validate->messages()->first());
        }
        // 验证用户是否存在
        $old = User::where('phone',$data['phone'])->first();
        if($old){
            throw new \Exception('用户已经存在!');
        }
        return true;
    }
}
